var proviceFirstStageName;
var addressCitySecondStageName;
var addressCountiesThirdStageName;
var addressDetailInfo;
var telNumber;
var userName;
var addressPostalCode;
function getUrlArgStr(){
    var q=location.search.substr(1);
    var qs=q.split('&');
    var argStr='';
    if(qs){
        for(var i=0;i<qs.length;i++){
            argStr+=qs[i].substring(0,qs[i].indexOf('='))+'='+qs[i].substring(qs[i].indexOf('=')+1)+'&';
        }
    }
    return argStr.substr(0,argStr.length-1);
}
function getappid() {
  return "wx5bf47679c84ef3c8"; //换成自已的appid
}
function getTimeStamp() {
  var timestamp = new Date().getTime();
  var timestampstring = timestamp.toString();//一定要转换字符串
  oldTimeStamp = timestampstring;
  return timestampstring;
}
//得到随机字符串
function getNonceStr() {
  var $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  var maxPos = $chars.length;
  var noceStr = "";
  for (i = 0; i < 32; i++) {
    noceStr += $chars.charAt(Math.floor(Math.random() * maxPos));
  }
  oldNonceStr = noceStr;
  return noceStr;
}
function getAddrSign(noceStr,ts){
    accesstoken = $.cookie('access_token');
    code = $.cookie('code');
    state = $.cookie('state');
    url = 'http://'+window.location.host+window.location.pathname+'?'+getUrlArgStr();
    forSign = 'accesstoken='+accesstoken+'&appid='+getappid()+'&noncestr='+noceStr+'&timestamp='+ts+'&url='+url
    var shaObj = new jsSHA("SHA-1", "TEXT");
    shaObj.update(forSign);
    var hash = shaObj.getHash("HEX");
    return hash
}

function getWxAddr(){
    noceStr = getNonceStr()
    ts = getTimeStamp()
    signstring = getAddrSign(noceStr,ts);
    WeixinJSBridge.invoke('editAddress',
      {
        "appId": getappid(),
        "scope": "jsapi_address",
        "signType": "sha1",
        "addrSign": signstring,
        "timeStamp": ts,
        "nonceStr": noceStr
      }
      ,
      function (res) {
        console.log(res);
        if (res.err_msg == 'edit_address:ok'){
            proviceFirstStageName = res.proviceFirstStageName;
            addressCitySecondStageName = res.addressCitySecondStageName;
            addressCountiesThirdStageName = res.addressCountiesThirdStageName;
            addressDetailInfo = res.addressDetailInfo;
            telNumber = res.telNumber;
            userName = res.userName;
            addressPostalCode = res.addressPostalCode;
            var content = '';
            content += '<span class="name">'+userName+'</span>';
            content += '<span class="tel">'+telNumber+'</span>';
            content += '<span class="address_txt address_txt_top">'+proviceFirstStageName+addressCitySecondStageName+addressCountiesThirdStageName+'</span>';
            content += '<span class="address_txt">'+addressDetailInfo+'</span>';
            $('#dt_address').html(content);
            $("#buy").attr("disabled",false);
        }


      });
}

$(function(){
    $(document).attr("title","确认订单");
     $("#buy").attr("disabled",true);

    $("#buy").click(function(event) {
        access_token = $.cookie('access_token')
        openid = $.cookie('openid')
        task_id = $.cookie('task_id')
        if (access_token != null && openid != null){
            $.post('/validToken',{'access_token':access_token, 'openid':openid}, function(data, status){
                    if(data.data == 'suc'){
                      $.post('/checkTask',{'task_id':task_id}, function(data, status){
                          if(data.result == "PENDING"){
                            $.post('/jsapi/pay', {quantity:$("#quantity").html(), itemid:$("#itemid").html(), 'proviceFirstStageName':proviceFirstStageName, 'addressCitySecondStageName':addressCitySecondStageName, 'addressCountiesThirdStageName':addressCountiesThirdStageName, 'addressPostalCode':addressPostalCode, 'addressDetailInfo':addressDetailInfo,'telNumber':telNumber, 'userName':userName}, function(data, status){
                                    console.log(data);
                                    WeixinJSBridge.invoke(
                                       'getBrandWCPayRequest', data.params,
                                       function(res){
                                           if(res.err_msg == "get_brand_wcpay_request:ok" ) {
                                                    $.post('/revokeTask',{'task_id':task_id});
                                                    swal({title: "棒极了!",   text: "您于"+moment().format('HH:mm:ss')+"成功购买了"+$("#quantity").html()+"个"+$("#title").html(),   type: "success",   showCancelButton: false,   confirmButtonText: "OK",   closeOnConfirm: false }, function(){ window.location.href = 'http://flashsales.tangle-up.top/itemlist/pay';});
                                           }     // 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回    ok，但并不保证它绝对可靠。
                                           else{ // release item if user pay failed
                                              swal({title: "支付失败",   text: "请到我的订单中查看待支付订单，超时订单将被系统收回",   type: "error",   showCancelButton: false,   confirmButtonText: "OK",   closeOnConfirm: false }, function(){ window.location.href = 'http://flashsales.tangle-up.top/itemlist/pay';});
                                           }
                                       }
                                   );
                            });
                          }
                          else{
                            swal({title: "订单超时",   text: "请重新下单",   type: "error",   showCancelButton: false,   confirmButtonText: "OK",   closeOnConfirm: false }, function(){ window.location.href = 'http://flashsales.tangle-up.top/itemlist/pay';});
                          }
                      });

                    }
            });
        }
    });

    countdown.setLabels(
        ' 毫秒| 秒| 分| 小时| 天| 周| 月| year| decade| century| millennium',
        ' 毫秒| 秒| 分| 小时| 天| 周| 月| year| decade| century| millennium',
        '',
        null,
        '0');
    end = moment($("#expire").html(), "YYYY-MM-DD HH:mm:ss");
    var timer  = setInterval(function(){
        $("#countdown").html("<strong>支付时间还剩\t</strong>"+countdown(moment(), end).toHTML("strong"));
        if (moment() >= end){
            clearInterval(timer);
            $("#countdown").html("<strong>已超时</strong>");
            $("#buy").attr("disabled",true);
        }
    },
    1000);

})
